Ext.define('BISC.view.FolderManagerWindow', {
  extend: 'Ext.window.Window',
  height: 400,
  id: 'folderManagerWindow',
  width: 500,
  layout: {
    type: 'border'
  },
  closeAction: 'hide',
  title: 'Folder Manager',
  modified: {},
  initComponent: function() {
    var me = this;

    Ext.applyIf(me, {
      dockedItems: [
        {
          xtype: 'toolbar',
          ui: 'footer',
          region: 'center',
          dock: 'bottom',
          items: [
            {
              xtype: 'tbfill'
            },
            {
              xtype: 'button',
              width: 75,
              text: 'Save',
              scope: me,
              handler: me.onSave
            },
            {
              xtype: 'button',
              width: 75,
              text: 'Cancel',
              scope: me,
              handler: me.doClose
            }
          ]
        }
      ],
      items: [
        {
          xtype: 'treepanel',
          id: 'folderManagerTree',
          border: false,
          store: 'FoldersStore',
          region: 'center',
          split: true,
          viewConfig: {
            singleSelect: true,
            rootVisible: false
          },
          scope: me,
          listeners: {
            beforeitemexpand: function( node, e ) {
                this.getStore().getProxy().extraParams.path = node.data.path;
            },
            checkchange: function( node, isChecked, e ) {
                Ext.getCmp('folderManagerWindow').modified[node.data.path] = isChecked;
            },
            itemcontextmenu: function(view, record, item, index, e) {
                e.stopEvent();
                var ctx = Ext.create('BISC.view.CtxMnuFolderManager', {record: record});
                ctx.showAt(e.getXY());
            }
          }
        }
      ]
    });

    me.callParent(arguments);
  },

  doClose: function(button, e, options) {
    // fire close event on parent
    this.hide();
  },

  onSave: function(button, e, options) {
    // fire save event on parent
    var monitors = [];
    for ( var path in this.modified ) {
        monitors.push({ path: path, enabled: this.modified[path] });
    }
    this.hide();
    Ext.data.JsonP.request({
        url: 'http://localhost:8888/monitors/update',
        params: {
            monitors: Ext.encode( monitors )
        },
        scope: this,
        callback: function( st, res ) {
            console.log( res );
            if ( res.success ) {
                Ext.StoreManager.lookup('FolderListStore').load();
            }
        }
    });
    this.modified = {};
  }

});
